package com.cnzhy.stream;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @Author: zhaoyan5
 */
public class TelnetUtil {

    private static final Integer THRESHOLD = 10;

    /**
     * 测试telnet 机器端口的连通性
     */
    public static boolean telnet(String hostname, int port, int timeout) {
        System.out.println("telnet www.zhaoyan5.com = " + port);
        Socket socket = new Socket();
        boolean isConnected = false;
        try {
            socket.connect(new InetSocketAddress(hostname, port), timeout); // 建立连接
            isConnected = socket.isConnected(); // 通过现有方法查看连通状态
        } catch (IOException e) {
            // 当连不通时，直接抛异常，异常捕获即可
        } finally {
            try {
                socket.close();   // 关闭连接
            } catch (IOException e) {

            }
        }
        return isConnected;
    }

    static class MyForkJoinTask extends RecursiveTask<Void> {
        // 子任务开始计算的值
        private Integer startValue;
        // 子任务结束计算的值
        private Integer endValue;

        public MyForkJoinTask(Integer startValue, Integer endValue) {
            this.startValue = startValue;
            this.endValue = endValue;
        }

        @Override
        protected Void compute() {
            if (endValue - startValue < THRESHOLD) { // 如果条件成立，说明这个任务所需要计算的数值分为足够小了
                boolean isConnected = telnet("www.zhaoyan5.com", startValue, 100);
                if (isConnected) {
                    System.out.println("telnet www.zhaoyan5.com" + startValue + "==>isConnected: " + true);
                }
            } else {
                // 否则再进行任务拆分，拆分成两个任务
                new MyForkJoinTask(startValue, (startValue + endValue) / 2).fork();
                new MyForkJoinTask((startValue + endValue) / 2 + 1, endValue).fork();
            }
            return null;
        }
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        // 这是Fork/Join框架的线程池
        ForkJoinPool pool = new ForkJoinPool();
        pool.submit(new MyForkJoinTask(1, 65535));
        try {
            System.out.printf("fork/Join耗时= %d，result = %s ", System.currentTimeMillis() - start, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
